package com.bridgeintelligent.tag.webserver.dim.mgmt.service.share;

import com.bridgeintelligent.tag.mapper.DimMapper;
import com.bridgeintelligent.tag.mapper.ShareMapper;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimData;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.IdWorker;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.entity.ShareRelation;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.model.ShareModel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description
 * @author: grp 2020-12-29 18:07
 **/
@AllArgsConstructor
@Service
@Slf4j
public class ShareServiceImpl implements IShareService{

    private ShareMapper shareMapper;
    private DimMapper dimMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void give(ShareModel shareModel) throws Exception {
        if(StringUtils.equals(shareModel.getSharedState(),"00")||StringUtils.equals(shareModel.getSharedState(),"01")){
            // 更新标签状态
            updateDimInfo(shareModel);
            shareMapper.deleteByDimId(shareModel.getDimId());
        }
        if(StringUtils.equals(shareModel.getSharedState(), "02")){
            updateDimInfo(shareModel);
            shareMapper.deleteByDimId(shareModel.getDimId());
            List<String> users = shareModel.getUsers();
            if(CollectionUtils.isEmpty(users)){
                return;
            }
            List<ShareRelation> relations = new ArrayList<>(16);
            Date current = new Date();
            users.forEach(user->{
                relations.add(ShareRelation.of().setId(IdWorker.nextId()).setDimId(shareModel.getDimId()).setUserId(user).setCreateTime(current));
            });
            shareMapper.save(relations);
        }
    }

    public void updateDimInfo(ShareModel shareModel) throws Exception{
        DimData data = new DimData();
        data.setDimId(shareModel.getDimId());
        data.setSharedState(shareModel.getSharedState());
        data.setUptTime(DateHelper.currentDateTime());
        dimMapper.shareUpdate(data);
    }

    @Override
    public ShareModel list(String dimId) {
        String sharedState = dimMapper.findSharedState(dimId);
        ShareModel model = new ShareModel();
        model.setDimId(dimId);
        model.setSharedState(sharedState);
        if(StringUtils.endsWith(sharedState, "02")){
            model.setUsers(shareMapper.findByDimId(dimId));
        }
        return model;
    }
}
